/*
 * Copyright 2005-2013 shopxx.net. All rights reserved.
 * Support: http://www.shopxx.net
 * License: http://www.shopxx.net/license
 */
package com.xiaorong.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xiaorong.Pageable;
import com.xiaorong.dao.RoleDao;
import com.xiaorong.entity.Role;

@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

	@Resource
	private RoleDao roleDao;

	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(Long id, ModelMap model) {
		if(id != null){
			model.addAttribute("role", roleDao.find(id));
		}
		return "/role/edit";
	}
	
	@ResponseBody
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public boolean save(Role role, RedirectAttributes redirectAttributes) {
		role.setIsSystem(false);
		role.setAdmins(null);
		if(!validator.validate(role).isEmpty()){
			return false;
		}
		roleDao.persist(role);
		return true;
	}


	@ResponseBody
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public boolean update(Role role) {
		if(!validator.validate(role).isEmpty()){
			return false;
		}
		Role pRole = roleDao.find(role.getId());
		if (pRole == null || pRole.getIsSystem()) {
			return false;
		}
		role.setAdmins(pRole.getAdmins());
		role.setIsSystem(pRole.getIsSystem());
		roleDao.merge(role);
		
		return true;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Pageable pageable, ModelMap model) {
		model.addAttribute("page", roleDao.findPage(pageable));
		return "/role/list";
	}

	@ResponseBody
	@RequestMapping(value = "/delete")
	public boolean delete(Long[] ids) {
		if (ids != null) {
			for (Long id : ids) {
				Role role = roleDao.find(id);
				if (role != null && (role.getIsSystem() || (role.getAdmins() != null && !role.getAdmins().isEmpty()))) {
					return false;
				}
			}
			for (Long id : ids){
				roleDao.remove(id);
			}
		}
		return true;
	}

}